import os
import glob
import docx
import pandas as pd


# 说明： 需要安装pandas和python-docx库


def one_file_count(file, file_extension, word):
    print(file)
    if file_extension == 'docx':
        doc = docx.Document(file)
        chars_count = sum(len(p.text) for p in doc.paragraphs)
    elif file_extension == 'txt':
        def read_fun(encoding):
            try:
                with open(file, 'r', encoding=encoding) as f:
                    return f.read()
            except:
                return None

        success = False
        for encoding in ['gbk', 'utf-8', 'gb2312', 'ansi', 'windows-1252']:
            """尝试各种编码，如果任意以中国没报错，就认为是那种编码
            当然如果确定txt是某种编码的，写法就更简单且运行也更快速稳定"""
            txt = read_fun(encoding)
            if txt:
                # print(txt)
                success = True
                chars_count = len(txt)
                break
        if not success:
            print(f'读{file}失败')
            chars_count = 0
    elif file_extension == 'doc' or file_extension == 'rtf':
        try:
            wb = word.Documents.Open(file)
            chars_count = sum(len(str(p)) for p in wb.paragraphs)
            wb.Close()
        except Exception as e:
            print(f'读{file}失败', e)
            chars_count = 0

    return {
        '文件夹': os.path.dirname(file),
        '文件名': os.path.basename(file),
        '字符数': chars_count,
    }


def all_files_count(docs_dir, file_extension):
    all_statics = []
    word = None
    if file_extension == 'doc' or file_extension == 'rtf':
        import win32com.client
        word = win32com.client.Dispatch("Word.Application")
        word.visible = False
    for file in glob.glob(f'{docs_dir}\**\*.{file_extension}', recursive=True):
        if '~$' in file:
            continue  # 跳过临时文件
        # print(file)
        res = one_file_count(file, file_extension, word)
        if res:
            all_statics.append(res)
    if file_extension == 'doc' or file_extension == 'rtf':
        word.Quit()
    df = pd.DataFrame.from_records(all_statics)
    output_file = os.path.join(docs_dir, "字符数.xlsx");
    df.to_excel(output_file)
    print(f'saved to {output_file}')


if __name__ == '__main__':
    docs_dir = r"C:\Users\yang.lei\Downloads\docs"
    # docs_dir = r"D:\dl\docs"
    # txt_dir = r"C:\Users\yang.lei\Downloads\txts"
    # txt_dir = r"D:\dl\txts"
    # txt_dir = r"D:\dl\无法统计字符的文件"
    # all_files_count(docs_dir,'docx') # 统计docx
    # all_files_count(txt_dir, 'txt')  # 统计txt
    # all_files_count(docs_dir, 'doc')  # 统计doc
    all_files_count(docs_dir, 'rtf')  # 统计doc
